import pygame
import random
import sys
import math

# 初始化Pygame
pygame.init()

# 游戏常量
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60

# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
PURPLE = (128, 0, 128)
ORANGE = (255, 165, 0)
BROWN = (165, 42, 42)
CYAN = (0, 255, 255)
PINK = (255, 192, 203)
GRAY = (128, 128, 128)
DOOR_BROWN = (139, 69, 19)  # 门的颜色
SKIN_COLOR = (255, 220, 177)  # 皮肤颜色
GRASS_GREEN = (34, 139, 34)  # 草地绿色
STONE_GRAY = (128, 128, 128)  # 石头灰色
STONE_DARK_GRAY = (100, 100, 100)  # 石头深灰色

# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("增强版贪吃蛇冒险游戏")

# 创建时钟对象
clock = pygame.time.Clock()

# 草地纹理类
class Grass:
    def __init__(self):
        self.grass_positions = []
        # 生成草地纹理点
        for _ in range(2000):  # 增加草地密度
            x = random.randint(0, SCREEN_WIDTH)
            y = random.randint(0, SCREEN_HEIGHT)
            height = random.randint(2, 5)
            self.grass_positions.append((x, y, height))
    
    def draw(self, screen):
        # 绘制动态草地
        for x, y, height in self.grass_positions:
            # 添加轻微的风吹动效果
            sway = pygame.time.get_ticks() // 100 % 10
            if sway > 5:
                sway = 10 - sway
            pygame.draw.line(screen, GRASS_GREEN, (x, y), (x + sway // 2, y - height), 1)

# 石头类（更真实的障碍物）
class Stone:
    def __init__(self, x, y, width=40, height=40, shape="rectangle"):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.shape = shape
        self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
        # 石头的细节特征
        self.cracks = []
        self.moss = []
        # 生成石头的裂缝
        for _ in range(random.randint(1, 3)):
            start_x = random.randint(self.x, self.x + self.width)
            start_y = random.randint(self.y, self.y + self.height)
            end_x = start_x + random.randint(-10, 10)
            end_y = start_y + random.randint(-10, 10)
            self.cracks.append(((start_x, start_y), (end_x, end_y)))
        # 生成石头上的苔藓
        for _ in range(random.randint(0, 2)):
            moss_x = random.randint(self.x, self.x + self.width)
            moss_y = random.randint(self.y, self.y + self.height)
            self.moss.append((moss_x, moss_y))
        
    def draw(self, screen):
        # 绘制石头主体
        pygame.draw.ellipse(screen, STONE_GRAY, self.rect)
        
        # 绘制石头的阴影，增加立体感
        shadow_rect = pygame.Rect(self.x + 5, self.y + 5, self.width, self.height)
        pygame.draw.ellipse(screen, STONE_DARK_GRAY, shadow_rect)
        
        # 绘制石头的高光
        highlight_rect = pygame.Rect(self.x - 2, self.y - 2, self.width // 2, self.height // 2)
        pygame.draw.ellipse(screen, (160, 160, 160), highlight_rect)
        
        # 绘制裂缝
        for start, end in self.cracks:
            pygame.draw.line(screen, (80, 80, 80), start, end, 1)
            
        # 绘制苔藓
        for moss_pos in self.moss:
            pygame.draw.circle(screen, (50, 150, 50), moss_pos, random.randint(1, 2))

# 玩家类（更复杂的外观）
class Player:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.width = 30
        self.height = 30
        self.speed = 5
        self.direction = "right"  # 面向方向: "up", "down", "left", "right"
        self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
        self.arm_angle = 0  # 手臂摆动角度
        self.arm_swing_direction = 1  # 手臂摆动方向
        self.walk_cycle = 0  # 行走周期
        
    def move(self, dx, dy, obstacles):
        # 更新面向方向
        if dx == -1:
            self.direction = "left"
        elif dx == 1:
            self.direction = "right"
        elif dy == -1:
            self.direction = "up"
        elif dy == 1:
            self.direction = "down"
            
        # 计算新位置
        new_x = self.x + dx * self.speed
        new_y = self.y + dy * self.speed
        
        # 创建新矩形用于碰撞检测
        new_rect = pygame.Rect(new_x, new_y, self.width, self.height)
        
        # 检查边界
        if new_x >= 0 and new_x <= SCREEN_WIDTH - self.width and \
           new_y >= 0 and new_y <= SCREEN_HEIGHT - self.height:
            
            # 检查与障碍物的碰撞
            collision = False
            for obstacle in obstacles:
                if new_rect.colliderect(obstacle):
                    collision = True
                    break
            
            # 如果没有碰撞，则更新位置
            if not collision:
                self.x = new_x
                self.y = new_y
                self.rect.x = self.x
                self.rect.y = self.y
                
                # 更新手臂摆动动画
                self.arm_angle += 0.2 * self.arm_swing_direction
                if self.arm_angle > 0.5 or self.arm_angle < -0.5:
                    self.arm_swing_direction *= -1
                    
                # 更新行走周期
                self.walk_cycle = (self.walk_cycle + 1) % 20
    
    def draw(self, screen):
        # 绘制身体（椭圆形）
        body_rect = pygame.Rect(self.x + self.width//4, self.y + self.height//3, self.width//2, self.height//2)
        pygame.draw.ellipse(screen, (0, 100, 0), body_rect)
        
        # 绘制头部
        head_x = self.x + self.width//2
        head_y = self.y + self.height//4
        pygame.draw.circle(screen, SKIN_COLOR, (head_x, head_y), 8)
        
        # 绘制帽子
        hat_points = [
            (head_x - 10, head_y - 5),
            (head_x + 10, head_y - 5),
            (head_x + 12, head_y - 10),
            (head_x - 12, head_y - 10)
        ]
        pygame.draw.polygon(screen, (200, 0, 0), hat_points)
        
        # 绘制眼睛
        eye_offset = 3 if self.direction in ["left", "right"] else 0
        eye_dy = 0 if self.direction in ["left", "right"] else (2 if self.direction == "down" else -2)
        pygame.draw.circle(screen, WHITE, (head_x - 3 + eye_offset, head_y - 2 + eye_dy), 2)
        pygame.draw.circle(screen, WHITE, (head_x + 3 + eye_offset, head_y - 2 + eye_dy), 2)
        pygame.draw.circle(screen, BLACK, (head_x - 3 + eye_offset, head_y - 2 + eye_dy), 1)
        pygame.draw.circle(screen, BLACK, (head_x + 3 + eye_offset, head_y - 2 + eye_dy), 1)
        
        # 绘制嘴巴
        mouth_y = head_y + 3
        pygame.draw.arc(screen, BLACK, (head_x - 3, mouth_y - 2, 6, 4), 0, 3.14, 1)
        
        # 绘制手臂（摆动效果）
        arm_length = 12
        arm_width = 3
        arm_offset_x = 0
        arm_offset_y = 0
        
        # 根据面向方向确定手臂位置
        if self.direction == "right":
            arm_offset_x = self.width//2 + 5
            arm_offset_y = self.height//2
        elif self.direction == "left":
            arm_offset_x = self.width//2 - 5
            arm_offset_y = self.height//2
        elif self.direction == "up":
            arm_offset_x = self.width//2
            arm_offset_y = self.height//2 - 5
        elif self.direction == "down":
            arm_offset_x = self.width//2
            arm_offset_y = self.height//2 + 5
            
        # 计算手臂末端位置（带摆动效果）
        arm_end_x = self.x + arm_offset_x
        arm_end_y = self.y + arm_offset_y
        
        if self.direction in ["left", "right"]:
            arm_end_y += arm_length * (1 if self.direction == "right" else -1) * abs(self.arm_angle)
        else:
            arm_end_x += arm_length * (1 if self.direction == "down" else -1) * abs(self.arm_angle)
            
        pygame.draw.line(screen, SKIN_COLOR, 
                        (self.x + arm_offset_x, self.y + arm_offset_y),
                        (arm_end_x, arm_end_y), arm_width)
        
        # 绘制另一只手臂
        if self.direction in ["left", "right"]:
            pygame.draw.line(screen, SKIN_COLOR, 
                            (self.x + self.width//2 - (arm_offset_x - self.width//2), self.y + arm_offset_y),
                            (self.x + self.width//2 - (arm_offset_x - self.width//2), self.y + arm_offset_y + arm_length * (1 if self.direction == "right" else -1) * abs(self.arm_angle)), arm_width)
        else:
            pygame.draw.line(screen, SKIN_COLOR, 
                            (self.x + arm_offset_x, self.y + self.height//2 - (arm_offset_y - self.height//2)),
                            (self.x + arm_offset_x + arm_length * (1 if self.direction == "down" else -1) * abs(self.arm_angle), self.y + self.height//2 - (arm_offset_y - self.height//2)), arm_width)
            
        # 绘制腿（行走效果）
        leg_offset = 3 * abs(self.walk_cycle - 10) / 10  # 行走时腿部摆动
        pygame.draw.line(screen, (0, 0, 100), 
                        (self.x + self.width//2 - 5, self.y + self.height//2 + 10),
                        (self.x + self.width//2 - 5, self.y + self.height//2 + 10 + leg_offset), 3)
        pygame.draw.line(screen, (0, 0, 100), 
                        (self.x + self.width//2 + 5, self.y + self.height//2 + 10),
                        (self.x + self.width//2 + 5, self.y + self.height//2 + 10 - leg_offset), 3)
        
    def get_rect(self):
        return self.rect

# 怪物类（更复杂的外观）
class Monster:
    def __init__(self, x, y, monster_type=1):
        self.x = x
        self.y = y
        self.width = 40  # 增大敌人体积
        self.height = 40  # 增大敌人体积
        self.type = monster_type
        self.speed = 2 if monster_type == 1 else (3 if monster_type == 2 else 2)
        self.direction = random.choice(["up", "down", "left", "right"])
        self.change_direction_timer = 0
        self.shoot_timer = 0  # 射击计时器
        self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
        self.arm_angle = 0  # 手臂摆动角度
        self.arm_swing_direction = 1  # 手臂摆动方向
        self.hit_timer = 0  # 被击中效果计时器
        self.walk_cycle = 0  # 行走周期
        
    def move(self, obstacles):
        # 更新手臂摆动动画
        self.arm_angle += 0.15 * self.arm_swing_direction
        if self.arm_angle > 0.4 or self.arm_angle < -0.4:
            self.arm_swing_direction *= -1
            
        # 定期改变方向
        self.change_direction_timer -= 1
        if self.change_direction_timer <= 0:
            self.direction = random.choice(["up", "down", "left", "right"])
            self.change_direction_timer = random.randint(30, 90)  # 30-90帧后再次改变方向
            
        # 根据方向移动
        dx, dy = 0, 0
        if self.direction == "up":
            dy = -1
        elif self.direction == "down":
            dy = 1
        elif self.direction == "left":
            dx = -1
        elif self.direction == "right":
            dx = 1
            
        # 计算新位置
        new_x = self.x + dx * self.speed
        new_y = self.y + dy * self.speed
        
        # 检查边界
        if new_x >= 0 and new_x <= SCREEN_WIDTH - self.width and \
           new_y >= 0 and new_y <= SCREEN_HEIGHT - self.height:
            
            # 创建新矩形用于碰撞检测
            new_rect = pygame.Rect(new_x, new_y, self.width, self.height)
            
            # 检查与障碍物的碰撞
            collision = False
            for obstacle in obstacles:
                if new_rect.colliderect(obstacle):
                    collision = True
                    break
            
            # 如果没有碰撞，则更新位置
            if not collision:
                self.x = new_x
                self.y = new_y
                self.rect.x = self.x
                self.rect.y = self.y
                
                # 更新行走周期
                self.walk_cycle = (self.walk_cycle + 1) % 20
    
    def draw(self, screen):
        # 如果被击中，绘制闪烁效果
        if self.hit_timer > 0:
            self.hit_timer -= 1
            if self.hit_timer % 4 < 2:  # 闪烁效果
                return
                
        # 根据类型绘制不同颜色的怪物
        body_color = YELLOW  # 普通怪物
        if self.type == 2:  # 快速怪物
            body_color = ORANGE
        elif self.type == 3:  # 强力怪物
            body_color = PURPLE
            
        # 绘制怪物身体（椭圆形）
        body_rect = pygame.Rect(self.x + self.width//6, self.y + self.height//4, self.width*2//3, self.height//2)
        pygame.draw.ellipse(screen, body_color, body_rect)
        
        # 绘制怪物头部
        head_x = self.x + self.width//2
        head_y = self.y + self.height//3
        pygame.draw.circle(screen, body_color, (head_x, head_y), 10)
        
        # 绘制眼睛
        eye_offset_x = 5 if self.direction == "right" else (-5 if self.direction == "left" else 0)
        eye_offset_y = 5 if self.direction == "down" else (-5 if self.direction == "up" else 0)
        pygame.draw.circle(screen, WHITE, (head_x - 5 + eye_offset_x, head_y - 3 + eye_offset_y), 3)
        pygame.draw.circle(screen, WHITE, (head_x + 5 + eye_offset_x, head_y - 3 + eye_offset_y), 3)
        pygame.draw.circle(screen, BLACK, (head_x - 5 + eye_offset_x, head_y - 3 + eye_offset_y), 1)
        pygame.draw.circle(screen, BLACK, (head_x + 5 + eye_offset_x, head_y - 3 + eye_offset_y), 1)
        
        # 绘制嘴巴
        mouth_y = head_y + 5
        if self.type == 3:  # 强力怪物有更可怕的嘴
            pygame.draw.ellipse(screen, RED, (head_x - 6, mouth_y - 2, 12, 6))
            # 绘制牙齿
            for i in range(5):
                tooth_x = head_x - 4 + i * 2
                pygame.draw.line(screen, WHITE, (tooth_x, mouth_y - 2), (tooth_x, mouth_y + 2), 1)
        else:
            pygame.draw.arc(screen, BLACK, (head_x - 4, mouth_y - 2, 8, 4), 0, 3.14, 1)
        
        # 绘制触角
        pygame.draw.line(screen, body_color, (head_x - 5, head_y - 8), (head_x - 8, head_y - 12), 2)
        pygame.draw.line(screen, body_color, (head_x + 5, head_y - 8), (head_x + 8, head_y - 12), 2)
        pygame.draw.circle(screen, (max(0, body_color[0]-50), max(0, body_color[1]-50), max(0, body_color[2]-50)), (head_x - 8, head_y - 12), 2)
        pygame.draw.circle(screen, (max(0, body_color[0]-50), max(0, body_color[1]-50), max(0, body_color[2]-50)), (head_x + 8, head_y - 12), 2)
        
        # 绘制手臂（摆动效果）
        arm_length = 10
        arm_width = 3
        arm_offset_x = self.width//2
        arm_offset_y = self.height//2
        
        # 计算手臂末端位置（带摆动效果）
        arm_end_x = self.x + arm_offset_x
        arm_end_y = self.y + arm_offset_y
        
        if self.direction in ["left", "right"]:
            arm_end_x += arm_length * (1 if self.direction == "right" else -1) * abs(self.arm_angle)
        else:
            arm_end_y += arm_length * (1 if self.direction == "down" else -1) * abs(self.arm_angle)
            
        pygame.draw.line(screen, 
                        (max(0, body_color[0]-50), max(0, body_color[1]-50), max(0, body_color[2]-50)), 
                        (self.x + arm_offset_x, self.y + arm_offset_y),
                        (arm_end_x, arm_end_y), arm_width)
        
        # 绘制另一只手臂
        if self.direction in ["left", "right"]:
            pygame.draw.line(screen, 
                            (max(0, body_color[0]-50), max(0, body_color[1]-50), max(0, body_color[2]-50)), 
                            (self.x + arm_offset_x, self.y + arm_offset_y),
                            (self.x + arm_offset_x - arm_length * (1 if self.direction == "right" else -1) * abs(self.arm_angle), self.y + arm_offset_y), arm_width)
        else:
            pygame.draw.line(screen, 
                            (max(0, body_color[0]-50), max(0, body_color[1]-50), max(0, body_color[2]-50)), 
                            (self.x + arm_offset_x, self.y + arm_offset_y),
                            (self.x + arm_offset_x, self.y + arm_offset_y - arm_length * (1 if self.direction == "down" else -1) * abs(self.arm_angle)), arm_width)
            
        # 绘制腿（行走效果）
        leg_offset = 3 * abs(self.walk_cycle - 10) / 10  # 行走时腿部摆动
        pygame.draw.line(screen, 
                        (max(0, body_color[0]-50), max(0, body_color[1]-50), max(0, body_color[2]-50)), 
                        (self.x + self.width//2 - 8, self.y + self.height//2 + 10),
                        (self.x + self.width//2 - 8, self.y + self.height//2 + 10 + leg_offset), 2)
        pygame.draw.line(screen, 
                        (max(0, body_color[0]-50), max(0, body_color[1]-50), max(0, body_color[2]-50)), 
                        (self.x + self.width//2 + 8, self.y + self.height//2 + 10),
                        (self.x + self.width//2 + 8, self.y + self.height//2 + 10 - leg_offset), 2)
        
        # 强力怪物有额外的装饰
        if self.type == 3:
            # 绘制背部刺
            for i in range(5):
                spike_x = self.x + self.width//2 - 10 + i * 5
                pygame.draw.line(screen, (max(0, body_color[0]-70), max(0, body_color[1]-70), max(0, body_color[2]-70)), 
                               (spike_x, self.y + self.height//3), (spike_x, self.y + self.height//3 - 8), 2)
    
    def shoot(self, player_x, player_y):
        # 第三关后敌人才能射击
        if self.type >= 2:
            self.shoot_timer -= 1
            if self.shoot_timer <= 0:
                self.shoot_timer = random.randint(90, 150)  # 降低射击频率(90-150帧)
                
                # 计算射击方向（朝向玩家）
                dx = player_x - (self.x + self.width//2)
                dy = player_y - (self.y + self.height//2)
                
                # 确定主要方向
                direction = "right"
                if abs(dx) > abs(dy):
                    if dx < 0:
                        direction = "left"
                else:
                    if dy < 0:
                        direction = "up"
                    else:
                        direction = "down"
                        
                # 创建敌人子弹
                return EnemyBullet(self.x + self.width//2, self.y + self.height//2, direction)
        return None
    
    def hit(self):
        # 被击中效果
        self.hit_timer = 10  # 设置闪烁时间

class Bullet:
    def __init__(self, x, y, direction, bullet_type="normal"):
        self.x = x
        self.y = y
        self.width = 8  # 增大子弹体积
        self.height = 8  # 增大子弹体积
        self.speed = 10
        self.direction = direction  # "up", "down", "left", "right"
        self.bullet_type = bullet_type  # "normal", "spread"
        self.angle = 0  # 用于扇形子弹的角度
        self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
        self.hit_target = False  # 是否击中目标
        
    def move(self, obstacles):
        # 根据方向移动
        if self.direction == "up":
            self.y -= self.speed
        elif self.direction == "down":
            self.y += self.speed
        elif self.direction == "left":
            self.x -= self.speed
        elif self.direction == "right":
            self.x += self.speed
            
        self.rect.x = self.x
        self.rect.y = self.y
        
        # 检查是否与障碍物碰撞
        for obstacle in obstacles:
            if self.rect.colliderect(obstacle):
                return False  # 子弹与障碍物碰撞，消失
                
        # 检查是否超出屏幕
        if self.x < 0 or self.x > SCREEN_WIDTH or self.y < 0 or self.y > SCREEN_HEIGHT:
            return False
        return True
    
    def draw(self, screen):
        # 根据子弹类型绘制不同颜色
        color = WHITE
        if self.bullet_type == "spread":
            color = CYAN
            
        pygame.draw.circle(screen, color, (self.x + self.width//2, self.y + self.height//2), self.width//2)

class EnemyBullet:
    def __init__(self, x, y, direction):
        self.x = x
        self.y = y
        self.width = 8  # 增大子弹体积
        self.height = 8  # 增大子弹体积
        self.speed = 5  # 降低敌人子弹速度
        self.direction = direction  # "up", "down", "left", "right"
        self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
        self.hit_target = False  # 是否击中目标
        
    def move(self, obstacles):
        # 根据方向移动
        if self.direction == "up":
            self.y -= self.speed
        elif self.direction == "down":
            self.y += self.speed
        elif self.direction == "left":
            self.x -= self.speed
        elif self.direction == "right":
            self.x += self.speed
            
        self.rect.x = self.x
        self.rect.y = self.y
        
        # 检查是否与障碍物碰撞
        for obstacle in obstacles:
            if self.rect.colliderect(obstacle):
                return False  # 子弹与障碍物碰撞，消失
                
        # 检查是否超出屏幕
        if self.x < 0 or self.x > SCREEN_WIDTH or self.y < 0 or self.y > SCREEN_HEIGHT:
            return False
        return True
    
    def draw(self, screen):
        pygame.draw.circle(screen, RED, (self.x + self.width//2, self.y + self.height//2), self.width//2)

class Game:
    def __init__(self):
        self.current_level = 1
        self.player = Player(50, SCREEN_HEIGHT // 2)
        self.obstacles = []
        self.monsters = []
        self.bullets = []
        self.enemy_bullets = []
        self.inventory = {
            "gun": False,
            "bullets": 0,
            "shield": False,
            "double_fire": False,
            "bullet_level": 1  # 子弹等级
        }
        self.reward_message = ""
        self.reward_message_timer = 0
        self.shoot_cooldown = 0  # 射击冷却计时器
        self.hit_effects = []  # 击中特效列表
        self.grass = Grass()  # 草地纹理
        self.setup_level(self.current_level)
        
    def setup_level(self, level):
        self.obstacles = []
        self.monsters = []
        self.bullets = []
        self.enemy_bullets = []
        self.hit_effects = []
        
        # 根据关卡设置障碍物和怪物，减少障碍物数量
        if level == 1:
            # 关卡1: 3个石头障碍物
            self.obstacles = [
                Stone(200, 100, 50, 50, "complex1"),
                Stone(500, 300, 50, 50, "complex2"),
                Stone(300, 400, 50, 50, "complex3")
            ]
            self.monsters = []
            
        elif level == 2:
            # 关卡2: 4个石头障碍物 + 2个怪物
            self.obstacles = [
                Stone(150, 100, 50, 50, "complex1"),
                Stone(350, 200, 50, 50, "complex2"),
                Stone(550, 100, 50, 50, "complex3"),
                Stone(350, 400, 50, 50, "complex1")
            ]
            self.monsters = [
                Monster(300, 150, 1),
                Monster(500, 350, 1)
            ]
            
        elif level == 3:
            # 关卡3: 5个石头障碍物 + 3个怪物
            self.obstacles = [
                Stone(100, 100, 50, 50, "complex1"),
                Stone(300, 200, 50, 50, "complex2"),
                Stone(500, 300, 50, 50, "complex3"),
                Stone(200, 400, 50, 50, "complex1"),
                Stone(600, 200, 50, 50, "complex2")
            ]
            self.monsters = [
                Monster(150, 200, 1),
                Monster(400, 300, 2),  # 快速怪物
                Monster(600, 400, 1)
            ]
            
        elif level == 4:
            # 关卡4: 6个石头障碍物 + 5个强力怪物
            self.obstacles = [
                Stone(50, 50, 50, 50, "complex1"),
                Stone(200, 150, 50, 50, "complex2"),
                Stone(400, 250, 50, 50, "complex3"),
                Stone(600, 350, 50, 50, "complex1"),
                Stone(150, 400, 50, 50, "complex2"),
                Stone(500, 100, 50, 50, "complex3")
            ]
            self.monsters = [
                Monster(200, 200, 3),  # 强力怪物
                Monster(400, 400, 3),  # 强力怪物
                Monster(600, 200, 2),  # 快速怪物
                Monster(150, 300, 1),
                Monster(350, 100, 2)   # 快速怪物
            ]
            
        elif level == 5:
            # 关卡5: 8个石头障碍物 + 8个各种怪物
            self.obstacles = [
                Stone(50, 50, 50, 50, "complex1"),
                Stone(200, 150, 50, 50, "complex2"),
                Stone(400, 250, 50, 50, "complex3"),
                Stone(600, 350, 50, 50, "complex1"),
                Stone(150, 400, 50, 50, "complex2"),
                Stone(500, 100, 50, 50, "complex3"),
                Stone(300, 500, 50, 50, "complex1"),
                Stone(700, 200, 50, 50, "complex2")
            ]
            self.monsters = [
                Monster(100, 200, 3),  # 强力怪物
                Monster(300, 300, 3),  # 强力怪物
                Monster(500, 400, 2),  # 快速怪物
                Monster(700, 100, 3),  # 强力怪物
                Monster(200, 450, 1),
                Monster(400, 150, 2),  # 快速怪物
                Monster(600, 500, 3),  # 强力怪物
                Monster(100, 500, 2)   # 快速怪物
            ]
    
    def handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and self.inventory["gun"]:
                    # 检查射击冷却
                    if self.shoot_cooldown <= 0:
                        # 根据子弹等级发射不同类型的子弹
                        if self.inventory["bullet_level"] >= 3:
                            # 三级子弹：扇形发射
                            self.shoot_spread_bullets()
                        elif self.inventory["bullet_level"] >= 2:
                            # 二级子弹：三发子弹
                            self.shoot_triple_bullets()
                        else:
                            # 一级子弹：普通射击
                            self.shoot_normal_bullets()
                        
                        # 设置射击冷却时间
                        self.shoot_cooldown = 15  # 15帧冷却时间
        return True
    
    def shoot_normal_bullets(self):
        # 普通射击
        if self.inventory["double_fire"]:
            # 双倍火力
            self.bullets.append(Bullet(self.player.x + self.player.width//2, self.player.y + self.player.height//2, self.player.direction))
            # 第二发子弹稍微偏移一点
            if self.player.direction in ["up", "down"]:
                self.bullets.append(Bullet(self.player.x + self.player.width//2 + 10, self.player.y + self.player.height//2, self.player.direction))
            else:
                self.bullets.append(Bullet(self.player.x + self.player.width//2, self.player.y + self.player.height//2 + 10, self.player.direction))
        else:
            # 普通射击
            self.bullets.append(Bullet(self.player.x + self.player.width//2, self.player.y + self.player.height//2, self.player.direction))
    
    def shoot_triple_bullets(self):
        # 三发子弹
        angle_offsets = [-0.2, 0, 0.2]  # 三发子弹的角度偏移
        
        for offset in angle_offsets:
            # 计算子弹方向
            if self.player.direction == "right":
                direction = (1, 0)
            elif self.player.direction == "left":
                direction = (-1, 0)
            elif self.player.direction == "up":
                direction = (0, -1)
            elif self.player.direction == "down":
                direction = (0, 1)
                
            # 应用角度偏移
            angle = math.atan2(direction[1], direction[0]) + offset
            new_direction_x = math.cos(angle)
            new_direction_y = math.sin(angle)
            
            # 确定新的方向字符串
            if abs(new_direction_x) > abs(new_direction_y):
                new_direction = "right" if new_direction_x > 0 else "left"
            else:
                new_direction = "down" if new_direction_y > 0 else "up"
            
            # 创建子弹
            bullet = Bullet(self.player.x + self.player.width//2, self.player.y + self.player.height//2, new_direction)
            self.bullets.append(bullet)
    
    def shoot_spread_bullets(self):
        # 扇形发射（5发子弹）
        angle_offsets = [-0.4, -0.2, 0, 0.2, 0.4]  # 五发子弹的角度偏移
        
        for offset in angle_offsets:
            # 计算子弹方向
            if self.player.direction == "right":
                direction = (1, 0)
            elif self.player.direction == "left":
                direction = (-1, 0)
            elif self.player.direction == "up":
                direction = (0, -1)
            elif self.player.direction == "down":
                direction = (0, 1)
                
            # 应用角度偏移
            angle = math.atan2(direction[1], direction[0]) + offset
            new_direction_x = math.cos(angle)
            new_direction_y = math.sin(angle)
            
            # 确定新的方向字符串
            if abs(new_direction_x) > abs(new_direction_y):
                new_direction = "right" if new_direction_x > 0 else "left"
            else:
                new_direction = "down" if new_direction_y > 0 else "up"
            
            # 创建扇形子弹
            bullet = Bullet(self.player.x + self.player.width//2, self.player.y + self.player.height//2, new_direction, "spread")
            self.bullets.append(bullet)
    
    def update(self):
        # 更新射击冷却计时器
        if self.shoot_cooldown > 0:
            self.shoot_cooldown -= 1
            
        # 处理玩家移动
        keys = pygame.key.get_pressed()
        dx, dy = 0, 0
        if keys[pygame.K_LEFT]:
            dx = -1
        if keys[pygame.K_RIGHT]:
            dx = 1
        if keys[pygame.K_UP]:
            dy = -1
        if keys[pygame.K_DOWN]:
            dy = 1
        self.player.move(dx, dy, self.obstacles)
        
        # 更新怪物
        for monster in self.monsters:
            monster.move(self.obstacles)
            
            # 检查怪物与玩家的碰撞
            if self.player.get_rect().colliderect(monster.rect):
                if not self.inventory["shield"]:
                    self.reset_level()
                    return
                else:
                    # 使用护盾
                    self.inventory["shield"] = False
                    self.monsters.remove(monster)
            
            # 敌人射击
            if self.current_level >= 3:
                enemy_bullet = monster.shoot(self.player.x, self.player.y)
                if enemy_bullet:
                    self.enemy_bullets.append(enemy_bullet)
        
        # 更新玩家子弹
        for bullet in self.bullets[:]:
            if not bullet.move(self.obstacles):  # 传递障碍物列表用于碰撞检测
                self.bullets.remove(bullet)
            else:
                # 检查子弹与怪物的碰撞
                for monster in self.monsters[:]:
                    if bullet.rect.colliderect(monster.rect):
                        # 强力怪物需要2发子弹才能消灭
                        if monster.type == 3:
                            monster.type = 1  # 变为普通怪物
                        else:
                            self.monsters.remove(monster)
                            
                        # 添加击中特效
                        self.hit_effects.append({
                            'x': monster.x + monster.width//2,
                            'y': monster.y + monster.height//2,
                            'timer': 15,
                            'color': YELLOW
                        })
                        
                        # 怪物被击中效果
                        monster.hit()
                        
                        if bullet in self.bullets:
                            self.bullets.remove(bullet)
                        break
        
        # 更新敌人子弹
        for bullet in self.enemy_bullets[:]:
            if not bullet.move(self.obstacles):  # 传递障碍物列表用于碰撞检测
                self.enemy_bullets.remove(bullet)
            else:
                # 检查敌人子弹与玩家的碰撞
                if bullet.rect.colliderect(self.player.get_rect()):
                    if not self.inventory["shield"]:
                        self.reset_level()
                        return
                    else:
                        # 使用护盾
                        self.inventory["shield"] = False
                        self.enemy_bullets.remove(bullet)
        
        # 更新击中特效
        for effect in self.hit_effects[:]:
            effect['timer'] -= 1
            if effect['timer'] <= 0:
                self.hit_effects.remove(effect)
        
        # 更新奖励消息计时器
        if self.reward_message_timer > 0:
            self.reward_message_timer -= 1
        
        # 检查玩家是否到达终点（右下角的门）
        door_rect = pygame.Rect(SCREEN_WIDTH - 100, SCREEN_HEIGHT - 150, 50, 100)
        if self.player.get_rect().colliderect(door_rect):
            self.next_level()
    
    def reset_level(self):
        # 重置关卡
        self.setup_level(self.current_level)
        self.player = Player(50, SCREEN_HEIGHT // 2)
        # 重置部分物品
        if self.inventory["shield"]:
            self.inventory["shield"] = False
        if self.inventory["double_fire"]:
            self.inventory["double_fire"] = False
        # 清除奖励消息
        self.reward_message = ""
        self.reward_message_timer = 0
        # 重置射击冷却
        self.shoot_cooldown = 0
    
    def next_level(self):
        # 进入下一关
        if self.current_level < 5:
            # 根据关卡给予奖励
            if self.current_level == 1:
                self.inventory["gun"] = True
                self.reward_message = "恭喜获得手枪！按空格键发射子弹来击败怪物。"
            elif self.current_level == 2:
                self.inventory["bullets"] += 10
                self.inventory["bullet_level"] = 2  # 子弹升级到二级
                self.reward_message = "恭喜获得子弹补给！子弹已升级为三发子弹。"
            elif self.current_level == 3:
                self.inventory["shield"] = True
                self.reward_message = "恭喜获得护盾！它可以保护你免受一次怪物攻击。"
            elif self.current_level == 4:
                self.inventory["double_fire"] = True
                self.inventory["bullet_level"] = 3  # 子弹升级到三级
                self.reward_message = "恭喜获得双倍火力！子弹已升级为扇形发射。"
                
            self.reward_message_timer = 300  # 显示5秒(60 FPS * 5)
            
            # 进入下一关
            self.current_level += 1
            self.setup_level(self.current_level)
            self.player = Player(50, SCREEN_HEIGHT // 2)
        else:
            # 游戏通关
            print("恭喜通关所有关卡！")
            pygame.quit()
            sys.exit()
    
    def draw(self):
        # 填充背景（清除上一帧）
        screen.fill(GRASS_GREEN)
        
        # 绘制草地背景
        self.grass.draw(screen)
        
        # 绘制障碍物（石头）
        for obstacle in self.obstacles:
            obstacle.draw(screen)
        
        # 绘制怪物
        for monster in self.monsters:
            monster.draw(screen)
        
        # 绘制玩家子弹
        for bullet in self.bullets:
            bullet.draw(screen)
            
        # 绘制敌人子弹
        for bullet in self.enemy_bullets:
            bullet.draw(screen)
        
        # 绘制击中特效
        for effect in self.hit_effects:
            pygame.draw.circle(screen, effect['color'], (effect['x'], effect['y']), 15 - effect['timer'])
        
        # 绘制玩家
        self.player.draw(screen)
        
        # 绘制终点区域（门的形状）
        # 门框
        pygame.draw.rect(screen, DOOR_BROWN, (SCREEN_WIDTH - 100, SCREEN_HEIGHT - 150, 50, 100))
        # 门内填充
        pygame.draw.rect(screen, BROWN, (SCREEN_WIDTH - 95, SCREEN_HEIGHT - 145, 40, 90))
        # 门把手
        pygame.draw.circle(screen, GRAY, (SCREEN_WIDTH - 90, SCREEN_HEIGHT - 100), 3)
        
        # 显示关卡信息和物品
        font = pygame.font.Font(None, 36)
        level_text = font.render(f"关卡: {self.current_level}", True, WHITE)
        screen.blit(level_text, (10, 10))
        
        # 显示物品信息
        y_offset = 50
        if self.inventory["gun"]:
            gun_text = font.render("武器: 手枪", True, WHITE)
            screen.blit(gun_text, (10, y_offset))
            y_offset += 30
            
        if self.inventory["bullets"] > 0:
            bullet_text = font.render(f"子弹: {self.inventory['bullets']}", True, WHITE)
            screen.blit(bullet_text, (10, y_offset))
            y_offset += 30
            
        if self.inventory["shield"]:
            shield_text = font.render("护盾: 已装备", True, WHITE)
            screen.blit(shield_text, (10, y_offset))
            y_offset += 30
            
        if self.inventory["double_fire"]:
            double_text = font.render("双倍火力: 已装备", True, WHITE)
            screen.blit(double_text, (10, y_offset))
            y_offset += 30
            
        # 显示子弹等级
        bullet_level_text = font.render(f"子弹等级: {self.inventory['bullet_level']}", True, WHITE)
        screen.blit(bullet_level_text, (10, y_offset))
            
        # 显示奖励消息
        if self.reward_message_timer > 0:
            reward_font = pygame.font.Font(None, 32)
            reward_text = reward_font.render(self.reward_message, True, YELLOW)
            # 居中显示
            text_rect = reward_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2))
            # 绘制半透明背景
            background_rect = pygame.Rect(text_rect.x - 10, text_rect.y - 10, text_rect.width + 20, text_rect.height + 20)
            pygame.draw.rect(screen, (0, 0, 0, 128), background_rect)
            pygame.draw.rect(screen, YELLOW, background_rect, 2)
            screen.blit(reward_text, text_rect)
            
        # 更新显示
        pygame.display.flip()

def main():
    game = Game()
    running = True
    
    while running:
        running = game.handle_events()
        game.update()
        game.draw()
        clock.tick(FPS)
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()


